package com.csjbot.csjbase.base;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.csjbot.csjbase.event.BusFactory;
import com.csjbot.csjbase.event.IBus;
import com.csjbot.csjbase.log.Csjlogger;

/**
 * Copyright (c) 2016, SuZhou CsjBot. All Rights Reserved.
 * www.csjbot.com
 * <p>
 * Created by 浦耀宗 at 2016/12/22 0022-18:13.
 * Email: puyz@csjbot.com
 */

public abstract class CsjBaseService extends Service {
    protected IBus ibus = null;

    /**
     * Return the communication channel to the service.  May return null if
     * clients can not bind to the service.  The returned
     * {@link IBinder} is usually for a complex interface
     * that has been <a href="{@docRoot}guide/components/aidl.html">described using
     * aidl</a>.
     * <p>
     * <p><em>Note that unlike other application components, calls on to the
     * IBinder interface returned here may not happen on the main thread
     * of the process</em>.  More information about the main thread can be found in
     * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html">Processes and
     * Threads</a>.</p>
     *
     * @param intent The Intent that was used to bind to this service,
     *               as given to {@link Context#bindService
     *               Context.bindService}.  Note that any extras that were included with
     *               the Intent at that point will <em>not</em> be seen here.
     * @return Return an IBinder through which clients can call on to the
     * service.
     */
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Csjlogger.info("==== {} started , using eventbus {}", this.getClass().getSimpleName(), useEventBus());

        if (useEventBus()) {
            ibus = BusFactory.getBus();
            ibus.register(this);
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return Service.START_STICKY;
    }

    @Override
    public void onDestroy() {
        if (ibus != null) {
            ibus.unregister(this);
        }
        super.onDestroy();
    }

    public boolean useEventBus() {
        return false;
    }

    public void postEvent(IBus.IEvent event) {
        if (ibus != null) {
//            Csjlogger.debug("postEvent  " + event.getTag());
            Csjlogger.debug("postEvent  " + event);
            ibus.post(event);
        }
    }

    public void postSticky(IBus.IEvent event) {
        if (ibus != null) {
            ibus.postSticky(event);
        }
    }
}
